import React, {Component} from 'react';
import {reqTypes, reqAddType, reqUpdateType, reqDeleteType} from "../../../api";
import {LIMIT} from "../../../config";
import {
    Table, message, Form, Input,
    Card, Button, Space, Modal,
    Popconfirm, Tag
} from "antd";
import {PlusOutlined, DeleteOutlined, EditOutlined} from '@ant-design/icons';

class Types extends Component {

    state = {
        dataSource: [],
        total: 0,
        isModalVisible: false,
        isAdd: false,
        typeId: 0,
        current: 1,
    }

    formRef = React.createRef();

    columns = [
        {
            title: '分类',
            dataIndex: 'typeName',
            render: (_, record) => {
                let {id, typeName} = record;
                return (id % 2 === 0) ? (
                    <Tag color="cyan">{typeName}</Tag>
                ) : (<Tag color="gold">{typeName}</Tag>)
            }
        },
        {
            title: '操作',
            render: (data) => {
                return (
                    <Space size="small">
                        <Button size="small"
                                icon={<EditOutlined/>}
                                onClick={() => this.initEditType(data)}/>
                        <Popconfirm
                            title="确定删除吗？"
                            onConfirm={() => this.deleteType(data)}
                            okText="确定"
                            cancelText="取消"
                        >
                            <Button size="small" icon={<DeleteOutlined/>} danger/>
                        </Popconfirm>
                    </Space>
                )
            }
        },
    ];

    // 回显数据
    initEditType = (data) => {
        let {id, typeName} = data;
        this.formRef.current.setFieldsValue({typeName});
        this.setState({isAdd: false, isModalVisible: true, typeId: id});
    }

    deleteType = async (data) => {
        let {status, msg} = await reqDeleteType(data.id);
        if (status === 0) {
            message.success(msg);
            this.initDataSource();
            return;
        }
        message.error(msg);
    }

    componentDidMount() {
        this.initDataSource();
    }

    initDataSource = async () => {
        let {current} = this.state;
        let {status, data} = await reqTypes(current);
        if (status === 1) {
            message.error("网络异常");
            return;
        }
        let {total, list} = data;
        let dataSource = list.reverse();
        this.setState({dataSource, total})
    }

    resetForm = () => {
        this.formRef.current.resetFields();
    }

    addType = () => {
        this.formValidate(reqAddType);
    }

    // 校验表单并提交数据
    formValidate = (func) => {
        this.formRef.current.validateFields().then(async value => {
            let {status, msg} = await func(value);
            if (status === 0) {
                this.initDataSource();
                message.success(msg);
                this.resetForm();
                this.setState({isModalVisible: false})
                return;
            }
            message.error(msg);
        }).catch(error => {
            let {errors} = error.errorFields[0];
            message.error(`${errors[0]}`)
            this.resetForm();
        });
    }

    editType = () => {
        this.formValidate(value => {
            value.id = this.state.typeId;
            return reqUpdateType(value);
        })
    }

    handleOk = () => {
        let {isAdd} = this.state;
        if (isAdd) {
            this.addType();
            return;
        }
        this.editType();
    }

    handleCancel = () => {
        this.setState({isModalVisible: false})
        this.resetForm();
    }

    // 分页
    pageChange = (pageInfo) => {
        let {current} = pageInfo;
        this.setState({current}, () => {
            this.initDataSource();
        });
    }

    render() {
        let {dataSource, total, isModalVisible, isAdd} = this.state;
        return (
            <div>
                <Card extra={<Button
                    type="primary"
                    icon={<PlusOutlined/>}
                    onClick={() => this.setState({isModalVisible: true, isAdd: true})}>添加分类</Button>}>
                    <Table
                        rowKey="id"
                        size="small"
                        onChange={this.pageChange}
                        pagination={{defaultPageSize: LIMIT, total, showTotal: (total) => `共 ${total} 条`}}
                        dataSource={dataSource}
                        columns={this.columns}/>
                </Card>
                <Modal title={isAdd ? "添加分类" : "编辑分类"}
                       forceRender={true}
                       okText="确定"
                       cancelText="取消"
                       visible={isModalVisible}
                       onOk={this.handleOk}
                       onCancel={this.handleCancel}>
                    <Form
                        name="basic"
                        ref={this.formRef}
                    >
                        <Form.Item
                            label="分类"
                            name="typeName"
                            rules={[
                                {
                                    required: true,
                                    message: '分类为必填项',
                                },
                            ]}
                        >
                            <Input placeholder="请输入分类名称"/>
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        );
    }
}

export default Types;